/**
 * Copyright &copy; 2012-2014 <a href="https://github.cn.apestar">JeeSite</a> All rights reserved.
 */
package cn.apestar.modules.sys.web;

import java.io.File;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.apestar.common.beanvalidator.BeanValidators;
import cn.apestar.common.config.Global;
import cn.apestar.common.image.FileUtilsIo;
import cn.apestar.common.utils.CacheUtils;
import cn.apestar.common.utils.CommonUtil;
import cn.apestar.common.utils.Encodes;
import cn.apestar.common.utils.StringUtils;
import cn.apestar.common.utils.excel.ImportExcel;
import cn.apestar.common.web.BaseController;
import cn.apestar.modules.sys.entity.Area;
import cn.apestar.modules.sys.entity.AreaExcel;
import cn.apestar.modules.sys.entity.User;
import cn.apestar.modules.sys.service.AreaService;
import cn.apestar.modules.sys.utils.UserUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 区域Controller
 * @author ThinkGem
 * @version 2013-5-15
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/area")
public class AreaController extends BaseController {

    @Autowired
    private AreaService areaService;

    @ModelAttribute("area")
    public Area get(@RequestParam(required = false) String id) {

        if (StringUtils.isNotBlank(id)) {
            return areaService.get(id);
        } else {
            return new Area();
        }
    }

    @RequestMapping(value = {"list" , ""})
    public String list(Area area, Model model) {

        model.addAttribute("list", areaService.findAll());
        return "modules/sys/area/areaList";
    }

    @RequestMapping(value = {"cityList"})
    public String cityList(Area area, Model model) {

        List<Area> list = areaService.findCnList(area);

        System.out.println(area.getName() + "," + area.getSort());

        model.addAttribute("list", list);
        model.addAttribute("area", area);
        return "modules/sys/area/cityList";
    }

    @RequestMapping(value = "updateType/{id}/{status}")
    public String updateType(@PathVariable("id") String id,@PathVariable("status") String status, RedirectAttributes redirectAttributes) {

        areaService.updateType(id,status);
        addMessage(redirectAttributes, "设置热门成功");
        return "redirect:" + Global.getAdminPath() + "/sys/area/cityList?repage";
    }

    @RequestMapping(value = "form")
    public String form(Area area, Model model) {

        area.setParent(areaService.get(area.getParent().getId()));
        model.addAttribute("area", area);
        return "modules/sys/area/areaForm";
    }

    @RequestMapping(value = "save")
    public String save(Area area, Model model, RedirectAttributes redirectAttributes) {

        if (!beanValidator(model, area)) {
            return form(area, model);
        }
        areaService.save(area);
        addMessage(redirectAttributes, "保存区域'" + area.getName() + "'成功");
        return "redirect:" + adminPath + "/sys/area/list";
    }

    @RequestMapping(value = "delete")
    public String delete(Area area, RedirectAttributes redirectAttributes) {

        areaService.delete(area);
        addMessage(redirectAttributes, "删除区域成功");
        return "redirect:" + adminPath + "/sys/area/list";
    }

    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId, HttpServletResponse response) {

        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<Area> list = areaService.findAll();
        for (int i = 0; i < list.size(); i++) {
            Area e = list.get(i);
            if (StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1)) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                map.put("pId", e.getParentId());
                map.put("name", e.getName());
                mapList.add(map);
            }
        }
        return mapList;
    }

    /**
     * 导入用户数据
     * @param file
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {

        try {
            CacheUtils.removeAll(ImportExcel.key);
            List dataList = areaService.findlist();
            Map map = CommonUtil.listToObject(dataList, "name");
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<AreaExcel> list = ei.getDataList(AreaExcel.class);
            for (AreaExcel areaExcel : list) {
                try {
                    if (!map.containsKey(areaExcel.getShengName())) {
                        map = areaService.saveSheng(areaExcel, map);
                    }

                    if (!map.containsKey(areaExcel.getCityName())) {
                        map = areaService.saveCity(areaExcel, map);
                    }

                    if (!map.containsKey(areaExcel.getQuName())) {
                        map = areaService.saveXian(areaExcel, map);
                    }

                    successNum++;
                } catch (ConstraintViolationException ex) {
                    List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
                    for (String message : messageList) {
                        failureMsg.append(message + "; ");
                        failureNum++;
                    }
                } catch (Exception ex) {
                    failureMsg.append(ex.getMessage() + "; ");
                    failureNum++;
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条用户，导入信息如下：");
            }
            addMessage(redirectAttributes, "已成功导入 " + successNum + " 条用户" + failureMsg);
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入用户失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + adminPath + "/sys/area/list?repage";
    }

    /**
     * 下载导入用户数据模板
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "import/template")
    public void importFileTemplate(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {

        try {
            String path = request.getSession().getServletContext().getRealPath("/");
            String typeName = request.getParameter("typeName");
            path = path + File.separator + "tpl" + File.separator + typeName + ".xlsx";
            String fileName = typeName + ".xlsx";
            List<User> list = Lists.newArrayList();
            list.add(UserUtils.getUser());
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + Encodes.urlEncode(fileName));
            FileUtilsIo.outputFileByPath(path, response.getOutputStream());
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
        }
    }
}
